package com.ykq.interceptor;

import com.alibaba.fastjson.JSON;
import com.ykq.util.CommonResult;
import com.ykq.util.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @program: springboot-vue
 * @description:
 * @author: 闫克起2
 * @create: 2022-01-04 16:40
 **/
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        String token = request.getHeader("token");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~"+token);
        if(request.getMethod().equals("OPTIONS")){
              return true;
        }
        if(token==null){
            PrintWriter writer = response.getWriter();
            CommonResult commonResult=new CommonResult(5002,"请先登录",null);
            writer.print(JSON.toJSONString(commonResult));
            return false;
        }else{
            try {
                JwtUtils.verifyToken(token);
                return true;
            }catch (Exception e){
                PrintWriter writer = response.getWriter();
                //token无效
                CommonResult commonResult=new CommonResult(5001,"token无效",null);
                writer.print(JSON.toJSONString(commonResult));
                return false;
            }
        }

    }
}




















